﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.Win32;

namespace SteveDower.SimpleBacklog
{
    /// <summary>
    /// This is the class that implements the package exposed by this assembly.
    ///
    /// The minimum requirement for a class to be considered a valid package for Visual Studio
    /// is to implement the IVsPackage interface and register itself with the shell.
    /// This package uses the helper classes defined inside the Managed Package Framework (MPF)
    /// to do it: it derives from the Package class that provides the implementation of the 
    /// IVsPackage interface and uses the registration attributes defined in the framework to 
    /// register itself and its components with the shell.
    /// </summary>
    // This attribute tells the PkgDef creation utility (CreatePkgDef.exe) that this class is
    // a package.
    [PackageRegistration(UseManagedResourcesOnly = true)]
    // This attribute is used to register the informations needed to show the this package
    // in the Help/About dialog of Visual Studio.
    [InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 400)]
    // This attribute is needed to let the shell know that this package exposes some menus.
    [ProvideMenuResource("Menus.ctmenu", 1)]
    // This attribute registers a tool window exposed by this package.
    [ProvideToolWindow(typeof(MyToolWindow))]
    [Guid(GuidList.guidSimpleBacklogPkgString)]
    public sealed class SimpleBacklogPackage : Package
    {
        /// <summary>
        /// Default constructor of the package.
        /// Inside this method you can place any initialization code that does not require 
        /// any Visual Studio service because at this point the package object is created but 
        /// not sited yet inside Visual Studio environment. The place to do all the other 
        /// initialization is the Initialize method.
        /// </summary>
        public SimpleBacklogPackage()
        {
            Solution = null;
            Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering constructor for: {0}", this.ToString()));
        }

        /// <summary>
        /// This function is called when the user clicks the menu item that shows the 
        /// tool window. See the Initialize method to see how the menu item is associated to 
        /// this function using the OleMenuCommandService service and the MenuCommand class.
        /// </summary>
        private void ShowToolWindow(object sender, EventArgs e)
        {
            // Get the instance number 0 of this tool window. This window is single instance so this instance
            // is actually the only one.
            // The last flag is set to true so that if the tool window does not exists it will be created.
            ToolWindowPane window = this.FindToolWindow(typeof(MyToolWindow), 0, true);
            if ((null == window) || (null == window.Frame))
            {
                throw new NotSupportedException(Resources.CanNotCreateWindow);
            }
            IVsWindowFrame windowFrame = (IVsWindowFrame)window.Frame;
            Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(windowFrame.Show());
        }

        private EnvDTE100.Solution4 _Solution;
        private EnvDTE100.Solution4 Solution
        {
            get
            {
                if (_Solution != null) return _Solution;
                
                var dte = GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
                if (dte == null || dte.Solution == null) return null;
                _Solution = dte.Solution as EnvDTE100.Solution4;
                if (_Solution != null && _Solution.IsOpen) return _Solution;
                _Solution = null;
                return null;
            }
            set
            {
                if (value == null) _Solution = null;
                else throw new NotSupportedException();
            }
        }
        private EnvDTE.Project SolutionItems
        {
            get
            {
                if (Solution == null) return null;
                foreach (var proj in Solution.Projects.OfType<EnvDTE.Project>())
                {
                    if (proj.Kind == EnvDTE.Constants.vsProjectKindSolutionItems) return proj;
                }
                return null;
            }
        }

        const string BacklogItemName = "Simple.Backlog";
        private string StoredData
        {
            get
            {
                if (Solution == null) return null;
                try
                {
                    var sourceItem = Solution.FindProjectItem(BacklogItemName);
                    var sourcePath = Path.Combine(Path.GetDirectoryName(Solution.FullName), BacklogItemName);
                    if (sourceItem == null && File.Exists(sourcePath))
                    {
                        var solnItems = SolutionItems;
                        if (solnItems == null) solnItems = Solution.AddSolutionFolder("Solution Items");
                        sourceItem = solnItems.ProjectItems.AddFromFile(sourcePath);
                    }
                    if (sourceItem == null) return null;

                    using (var file = new FileStream(sourceItem.FileNames[1], FileMode.Open, FileAccess.Read, FileShare.Read))
                    using (var reader = new StreamReader(file, System.Text.Encoding.Unicode))
                    {
                        return reader.ReadToEnd();
                    }
                }
                catch (ArgumentException)
                {
                    return null;
                }
            }
            set
            {
                if (Solution == null) return;

                EnvDTE.Project solnItems = SolutionItems;
                EnvDTE.ProjectItem sourceItem = null;
                string sourcePath;
                try
                {
                    sourceItem = Solution.FindProjectItem(BacklogItemName);
                    if (sourceItem == null) throw new ArgumentException();  // using exceptions for control flow - yay!
                    sourcePath = sourceItem.FileNames[1];
                }
                catch(ArgumentException)
                {
                    sourcePath = Path.Combine(Path.GetDirectoryName(Solution.FullName), BacklogItemName);
                }

                if (value == null)
                {
                    File.Delete(sourcePath);
                    if (sourceItem != null)
                    {
                        sourceItem.Delete();
                        Solution.Saved = false;
                    }
                    if (solnItems != null && solnItems.ProjectItems.Count == 0)
                    {
                        solnItems.Delete();
                        Solution.Saved = false;
                    }
                }
                else
                {
                    using (var file = new FileStream(sourcePath, FileMode.Create, FileAccess.Write, FileShare.None))
                    using (var writer = new StreamWriter(file, System.Text.Encoding.Unicode))
                    {
                        writer.Write(value);
                    }

                    if (solnItems == null) solnItems = Solution.AddSolutionFolder("Solution Items");
                    if (sourceItem == null) sourceItem = solnItems.ProjectItems.AddFromFile(sourcePath);
                }
            }
        }

        public void Reload()
        {
            var items = new List<BacklogItem>();
            try
            {
                using (var reader = new StringReader(StoredData))
                {
                    for (var line = reader.ReadLine(); line != null; line = reader.ReadLine())
                    {
                        try
                        {
                            items.Add(BacklogItem.Parse(line));
                        }
                        catch (FormatException ex)
                        {
                            Trace.WriteLine(ex.ToString());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine("Error opening Simple.backlog:\r\n" + ex.ToString());
                return;
            }

            ToolWindowPane window = this.FindToolWindow(typeof(MyToolWindow), 0, true);
            BacklogView content = (window == null) ? null : window.Content as BacklogView;
            if (content == null) Trace.WriteLine("Unable to create window.");
            else content.SetItems(items);
        }

        public void Save()
        {
            if (Solution == null || !Solution.IsOpen) return;

            ToolWindowPane window = this.FindToolWindow(typeof(MyToolWindow), 0, false);
            BacklogView content = (window == null) ? null : window.Content as BacklogView;
            if (content == null) { Trace.WriteLine("Unable to find window."); return; }

            if (content.Items.Count > 0)
            {
                using (var writer = new StringWriter())
                {
                    foreach (var item in content.Items.OrderBy(bi => bi.Index))
                    {
                        writer.WriteLine(item.ToString());
                    }
                    StoredData = writer.GetStringBuilder().ToString();
                }
            }
            else
            {
                StoredData = null;
            }

            content.SetItems(null);
            Solution = null;
        }

        private EnvDTE.SolutionEvents SolutionEvents;
        
        private void Solution_Opened()
        {
            Reload();
        }

        void Solution_BeforeClosing()
        {
            Save();
        }

        /////////////////////////////////////////////////////////////////////////////
        // Overriden Package Implementation
        #region Package Members

        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initilaization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString()));
            base.Initialize();

            // Add our command handlers for menu (commands must exist in the .vsct file)
            OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
            if (null != mcs)
            {
                // Create the command for the tool window
                CommandID toolwndCommandID = new CommandID(GuidList.guidSimpleBacklogCmdSet, (int)PkgCmdIDList.cmdidSimpleBacklogWindow);
                MenuCommand menuToolWin = new MenuCommand(ShowToolWindow, toolwndCommandID);
                mcs.AddCommand(menuToolWin);
            }
            var dte = GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
            if (null != dte)
            {
                SolutionEvents = dte.Events.SolutionEvents;
                SolutionEvents.Opened += new EnvDTE._dispSolutionEvents_OpenedEventHandler(Solution_Opened);
                SolutionEvents.BeforeClosing += new EnvDTE._dispSolutionEvents_BeforeClosingEventHandler(Solution_BeforeClosing);

                if (Solution != null)
                {
                    Solution_Opened();
                }
            }
        }

        #endregion



    }
}
